package dao;

import java.io.Serializable;
import java.util.List;
import tables.AdminTable;
import com.epam.grsulab.webapi.dao.AbstractDao;
import entity.Admin;

public class AdminDao extends AbstractDao<AdminTable, Admin> {

	public AdminDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Admin newAdmin) {
		// set ID
		newAdmin.setId(getNextId());
		// get existing data
		final AdminTable adminTable = deserializeFromXml();
		// add new row
		adminTable.getRows().add(newAdmin);
		// save data
		serializeToXml(adminTable);
	}

	@Override
	public void update(final Admin entity) {
		// get existing data
		final AdminTable adminTable = deserializeFromXml();
		// find by ID
		for (final Admin row : adminTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setPassword(entity.getPassword());
				break;
			}
		}
		// save updated table
		serializeToXml(adminTable);
	}

	@Override
	public Admin get(final Serializable id) {
		// get existing data
		final AdminTable adminTable = deserializeFromXml();
		// find by ID
		for (final Admin row : adminTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Admin> getAll() {
		// get existing data
		final AdminTable adminTable = deserializeFromXml();
		return adminTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		// get existing data
		final AdminTable adminTable = deserializeFromXml();
		// find by ID
		Admin toBeDeleted = null;
		for (final Admin row : adminTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		adminTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(adminTable);
	}

	@Override
	protected Class<AdminTable> getTableClass() {
		return AdminTable.class;
	}
}

